<?php


namespace app\api\model;

use app\api\service\Token;
use think\facade\Cache;
use think\exception\HttpException;
use app\api\enum\User as UserEnum;
use app\api\service\Token as TokenService;

class User extends Base
{
    // 用户登录
    public static function userLogin($data){

        $res = self::where(['nickname'=>$data['username'],'password'=>md5($data['password'])])->find();
        if(!$res){
            throw new HttpException(200,'账号或密码错误');
        }
        // 存入缓存
        Cache::store('redis')->set('uid',$res['id']);
        // 登录成功 生成token
        $tokenStr = TokenService::creatToken($res['id']);

        return ['userinfo'=>$res,'token'=>$tokenStr];
    }

    // 注册用户
    public static function userRegister($data){
        $username = self::where('nickname',$data['username'])->field('nickname')->find();

        if($username) throw new HttpException(200,'用户名已存在');

        if($data['password'] !== $data['confirmPassword']) throw new HttpException(500,'两次密码输入不一致');

        $arr = [
            'nickname'=>$data['username'],
            'headimgurl'=>'http://www.chat.com/chat/public/static/newcj/img/123.jpg',
            'password'=>md5($data['password']),
            'mpid'=>1,
            'sex'=> UserEnum::M
        ];
        $res = self::insert($arr);
        if($res){
            return $res;
        }
        throw new HttpException(500,'注册失败,内部错误');
    }

    // 根据uid查询用户姓名
    public static function getIdName($uid) :string {
        $res = self::where('id',$uid)->field('nickname')->find();
        if(!$res){
            throw new HttpException(500,'用户不存在');
        }
        return $res['nickname'];
    }

    // 根据uid查询当前聊天双方头像
    public static function getHeadImg($uid){
        $fromImg = self::where('id',$uid['fromid'])->field('headimgurl')->find();
        $toImg = self::where('id',$uid['toid'])->field('headimgurl')->find();
        if(!$fromImg || !$toImg){
            throw new HttpException(500,'用户不存在');
        }
        return ['fromImg' => $fromImg['headimgurl'], 'toImg' => $toImg['headimgurl']];
    }

    // 根据uid获取用户昵称
    public static function getNickName($uid){
        $uname = self::where('id',$uid)->field('nickname')->find();
        if(!$uname){
            throw new HttpException(500,'用户不存在');
        }
        return $uname;
    }

    // 根据uid获取单个用户头像
    public static function getHeadOne($uid){
        $fromhead = self::where('id',$uid)->field('headimgurl')->find();
        if(!$fromhead){
            return "";
        }
        return $fromhead['headimgurl'];
    }

    // 根据用户名查找用户
    public static function getUsernameList($data){
        if($data['value'] == "")return [];

        $where = [
            ['nickname', 'like', $data['value']. '%'],
            ['isvalid', '=', UserEnum::type],
            ['id', '<>', $data['id']]
        ];
        $users = self::where($where)->field(['id','nickname','headimgurl','sex'])->select()->toArray();

        return $users;
    }
}